<?php
// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;
//use app\common\validate\ShopRoles as Validate;
use think\Validate;

class ShopRoles extends Model
{
	/**
     * 错误信息
     */
	public $errorInfo;
	
	/**
     * 获取
     * @param type $uid
     * @return type
     */
	public function getList($shopId)
    {
    	$model = new self;
    	$model = $model->where('shop_id', $shopId);
    	$model = $model->order('sort_no','asc');
		return $model->select();
    }
	
	/**
     * 添加
     * @param type $uid
     * @return type
     */
	public function addRoles($param){
    	$validate = new Validate;
		$validate->rule([
		    'shop_id' => 'require',
        	'name' => 'require'
		]);
        if( !$validate->check($param) ) {
        	$this -> errorInfo = $validate->getError();
            return false;
        }
		if( self::where('name',$param['name'])->where('shop_id',$param['shop_id'])->find() ) {
        	$this -> errorInfo = '名称已存在！';
            return false;
        }
		return self::allowField(true) -> save($param);
    }

	/**
     * 编辑
     * @param type $uid
     * @return type
     */
	public function editRoles($param){
    	$validate = new Validate;
		$validate->rule([
			'id'=>'require',
        	'name' => 'require'
		]);
        if( !$validate->check($param) ) {
        	$this -> errorInfo = $validate->getError();
            return false;
        }
		if( self::where('name',$param['name'])->where('id','<>',$param['id'])->find() ) {
        	$this -> errorInfo = '名称已存在！';
            return false;
        }
		self::allowField(['name','rules','sort_no']) -> save($param,['id'=>$param['id']]);
		return true;
    }

	
	/**
     * 删除
     * @param type $uid
     * @return type
     */
	public function delRoles($shopId,$id){
		if( model('shop_staff')->where('shop_id',$shopId)->where('roles_id',$id)->find() ) {
        	$this -> errorInfo = '该角色下存在员工，不允许删除！';
            return false;
        }
		//更新为删除状态
		$result = $this->where('shop_id',$shopId)->where('id',$id)->delete();
		if(!$result){
			$this -> errorInfo = '没有该角色！';
            return false;
		}
		//返回成功通知
		return true;
    }
	
}
